import React, {useState, forwardRef, useImperativeHandle, useEffect, useRef} from 'react';
import {Button, Form, Input, message, Modal, Radio, Space, Upload} from "antd";
import ImgCrop from 'antd-img-crop';
import {uploadAvatar, editUserApi} from "./PersonalDataApi"
import rules from "../../utils/formVerify";

const SetPersonalData = forwardRef((props, ref) => {
        const [isModalOpen, setIsModalOpen] = useState(false);
        const [userData, setUserData] = useState({})
        const [fileList, setFileList] = useState([]);
        const formRef = useRef()
        const showModal = () => {
            setIsModalOpen(true);
        };

        // 提交方法
        const handleOk = async () => {
                try {
                    const data = await formRef.current.validateFields()
                    data.userPhotoUrl = fileList.length ? fileList[0].url : ''
                    editUserApi(data).then(res => {
                        if (res.code === '200') {
                            message.success('编辑成功')
                            props.getUserfun()
                            setIsModalOpen(false);
                        }
                    }).catch(e => {
                        console.log(e)
                    })
                } catch (e) {
                    console.log(e)
                }

            }
        ;

        // 输入框修改值
        const handleChange = (e, key) => {
            setUserData({...userData, [key]: e.target.value})
        }

        const handleCancel = () => {
            setIsModalOpen(false);
        };


        // 页面初始化
        useEffect(() => {
            if (!isModalOpen) return;
            const data = {
                userNumber: props.userData.userNumber,
                userEmail: props.userData.userEmail,
                userName: props.userData.userName,
                userPhone: props.userData.userPhone,
                userSex: props.userData.userSex,
                userPhotoUrl: props.userData.userPhotoUrl,
            }
            formRef.current.setFieldsValue(data)
            if (!props.userData.userPhotoUrl) return
            const imgItem = {
                uid: '-1',
                name: 'image.png',
                status: 'done',
                url: props.userData.userPhotoUrl,
            }
            setFileList([imgItem])
        }, [isModalOpen])

        //更换头像
        const onChange = ({fileList: newFileList}) => {
            setFileList(newFileList);
        };

        // 图片上传之前
        const beforeUpload = (file) => {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
            if (!isJpgOrPng) {
                message.error('图片类型不对!');
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                message.error('图片大小不能大于 2MB!');
            }
            return isJpgOrPng && isLt2M;
        };

        // 头像上传
        const doImgUpload = (options) => {
            const {file} = options;
            const imgItem = {
                uid: '1', // 注意，这个uid一定不能少，否则上传失败
                name: 'Avatar.png',
                status: 'uploading',
                url: '',
                percent: 99, // 注意不要写100。100表示上传完成
            };
            setFileList([imgItem]);
            const formData = new FormData()
            formData.append('file', file)
            uploadAvatar(formData).then(res => {
                if (res.code === '200') {
                    const imgItem = {
                        uid: '1', // 注意，这个uid一定不能少，否则上传失败
                        name: 'Avatar.png',
                        status: 'done',
                        url: process.env.REACT_APP_URL + res.url,
                        percent: 100, // 注意不要写100。100表示上传完成
                        response: '{"status": "success"}',
                    };
                    setFileList([imgItem]);
                    message.success('图片上传成功');
                    setUserData({...userData, userPhotoUrl: res.url})
                }
            }).catch(e => {
                message.error('图片上传失败，请重试');
            })
        }

        //抛出子组件的属性
        useImperativeHandle(ref, () => {
            return {
                showModal
            }
        })

        return (
            <>
                <Modal title="我的资料~~"
                       width={400}
                       open={isModalOpen}
                       footer=""
                       onCancel={handleCancel}>
                    <div style={{display: "flex", justifyContent: "center"}}>
                        <div>
                            <ImgCrop rotationSlider>
                                <Upload
                                    listType="picture-circle"
                                    action="#"
                                    fileList={fileList}
                                    maxCount={1}
                                    name={'file'}
                                    onChange={onChange}
                                    beforeUpload={beforeUpload}
                                    customRequest={doImgUpload}
                                >
                                    {fileList.length === 0 && '+ Upload'}
                                </Upload>
                            </ImgCrop>
                        </div>
                    </div>
                    <div style={{textAlign: 'center'}}>
                        <Form
                            ref={formRef}
                            name="editMyText"
                            labelCol={{span: 6,}}
                            wrapperCol={{span: 16,}}
                            style={{maxWidth: 600,}}
                            initialValues={{remember: true,}}
                            autoComplete="off"
                        >
                            <Form.Item
                                rules={rules[0]}
                                name="userNumber"
                                label="账号"
                            >
                                <Input value={userData.userNumber} disabled/>
                            </Form.Item>
                            <Form.Item
                                rules={rules[2]}
                                name="userName"
                                label="昵称"
                            >
                                <Input value={userData.userName}
                                       onChange={(e) => handleChange(e, 'userName')}/>
                            </Form.Item>
                            <Form.Item
                                rules={rules[5]}
                                name="userSex"
                                label="性别">
                                <Radio.Group value={userData.userSex}
                                             onChange={(e) => handleChange(e, 'userSex')}>
                                    <Radio value="男"> 男 </Radio>
                                    <Radio value="女"> 女 </Radio>
                                </Radio.Group>
                            </Form.Item>
                            <Form.Item
                                label="手机"
                                name="userPhone"
                                rules={rules[3]}
                            >
                                <Input value={userData.userPhone}
                                       onChange={(e) => handleChange(e, 'userPhone')} disabled/>
                            </Form.Item>
                            <Form.Item
                                label="邮箱"
                                name="userEmail"
                                rules={rules[4]}
                            >
                                <Input value={userData.userEmail}
                                       onChange={(e) => handleChange(e, 'userEmail')}/>
                            </Form.Item>
                        </Form>
                    </div>
                    <div style={{marginTop: '20px', display: 'flex', justifyContent: 'center'}}>
                        <Space> <Button onClick={handleCancel}>取消</Button></Space>
                        <Space> <Button type="primary" onClick={handleOk}>提交</Button></Space>
                    </div>
                </Modal>
            </>
        );
    }
)

export default SetPersonalData;
